package com.easyattendance.servlets;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.easyattendance.model.Assignment;
import com.easyattendance.model.Material;
import com.easyattendance.model.Teacher;
import com.easyattendance.nls.UseProperties;
import com.easyattendance.services.AddAssignmentService;
import com.easyattendance.services.AddMaterialService;
import com.easyattendance.services.AddSubjectService;
import com.easyattendance.services.AddTeacherService;

@WebServlet("/AddAssignmentServlet")
@MultipartConfig
public class AddAssignmentServlet extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
	private boolean error=false;
	public String path=null;
	public String message=null;
    
	protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		boolean dispatcherFlag = false;
		boolean result = false;
		AddSubjectService subjectService=new AddSubjectService();
		AddAssignmentService assService=new AddAssignmentService();
		AddTeacherService teacherService=new AddTeacherService();

		 String actionType = request.getParameter("action_type");
		
		 String ID=null;
		 
		 if(actionType.equals("create"))
		 {
			 
			 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Date ass_date = null;
				Date ass_sub_date = null;
				
				String ass_no=request.getParameter("assignment_id");
			 	String ass_name=request.getParameter("assignment_name");
			 	String class_id=request.getParameter("class_id");
				String subject_name=request.getParameter("subject_name");
				String file_location=path+"\\"+request.getParameter("file_name");
				String teacher_id=request.getParameter("teacher_id");				
				String ass_given_date=request.getParameter("assignment_date");
				String ass_submission=request.getParameter("assignment_sub_date");
				
				if(ass_name==null || class_id==null || subject_name==null || file_location==null || ass_given_date.isEmpty() || ass_submission.isEmpty())
				{ 
					request.setAttribute("null_values", "All * values are required.");
		        	dispatcherFlag = true;  
				}
				
				if(!dispatcherFlag)
				{
					String subject_id=subjectService.getSubjectIdBySubjectName(subject_name);
					try {
						ass_date=format.parse(ass_given_date);
						ass_sub_date=format.parse(ass_submission);
						
						if(ass_date==null || ass_sub_date==null)
						{
							request.setAttribute("date_null_values", "Dates cannot be null.");
				        	dispatcherFlag = true;  
						}
						
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
					Properties labels = UseProperties.loadProperties("Attendance.properties");
	            	labels = UseProperties.incrementAssignmentIdCounterValue(labels);
	            	ID = UseProperties.getAssignmentIdPrefix(labels)+ass_no;
	            	
					Teacher teacher=teacherService.getTeacherById(teacher_id);
					Assignment assignment=new Assignment(ID,subject_id,class_id,ass_name,file_location,ass_date,ass_sub_date);
					assignment.setTeacher(teacher);
					
					boolean res=assService.ifAlreadyExists(assignment);
					
					
					if(!res)
					{
						 result=assService.addAssignment(assignment);
					}
					else
					{
						if(!error)
						{	
							request.setAttribute("AssignmentExists", "Assignment is already uploaded.");
				        	dispatcherFlag=true;
						}
					}
					
					if(result)
					{
						if(!error)
						{	
							request.setAttribute("assignmentAdded", "Assignment uploaded successfully.");
							dispatcherFlag=true;
						}  
						else
					    {
						        request.setAttribute("file_upload_error",message);
						        dispatcherFlag=true;
					    }
					}
					else
					{
						if(!error)
						{
							request.setAttribute("assignmentNotAdded", "Assignment could not be uploaded.");
							dispatcherFlag=true;
							
							Properties label1 = UseProperties.loadProperties("Attendance.properties");
			            	label1 = UseProperties.decrementAssignmentIdCounterValue(label1);
						}
						else
					    {
						        request.setAttribute("file_upload_error",message);
						        dispatcherFlag=true;
					    }
					}
				}
				
				if(dispatcherFlag)
				{
					RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addAssignment.jsp");
		        	rd.forward(request, response);
				}
		 
		 }
		 else if(actionType.equals("delete")) {
				
				String assignments[] = request.getParameterValues("assignment_id");
				int res_flag=0;
				
				 String checkbox_list[]=new String[assignments.length];
				 
				 for(int i=0;i<assignments.length;i++)
				 {
						   checkbox_list[i]=request.getParameter("checkbox"+(i+1));
				 }
				 
				String classes[] = request.getParameterValues("class_id");
				String subjectNames[] = request.getParameterValues("subject_name");
				
				for(int i=0;i<assignments.length;i++)
				{
					 if(checkbox_list[i]!=null)
					 {
						   String assignmentId=assignments[i];
						   String classId=classes[i];
						   String subjectId=subjectService.getSubjectIdBySubjectName(subjectNames[i]);
						   
						   boolean res=assService.deleteAssignmentStudent(assignmentId,classId,subjectId);
						   boolean res1 =assService.deleteAssignment(assignmentId,classId,subjectId);
						   
						   if(!res1 && res)
							    res_flag++;
					 }
						 
				}
				
				if(res_flag==0){
					//out.println("Class deleted successfully");
					request.setAttribute("assignmentDeleted", "Assignments deleted successfully.");
		        	/*RequestDispatcher rd = request.getRequestDispatcher("views/teacher/assignmentSettings.jsp");
		        	rd.forward(request, response);*/
					response.sendRedirect("views/teacher/assignmentSettings.jsp");
				}
				else if(res_flag>0){
					//out.println("Class CANNOT be deleted successfully");
					request.setAttribute("assignmentNotDeleted", "Assignment Not deleted successfully.");
		        	/*RequestDispatcher rd = request.getRequestDispatcher("views/teacher/assignmentSettings.jsp");
		        	rd.forward(request, response); */
					response.sendRedirect("views/teacher/assignmentSettings.jsp");
				}
			}
		 else {
			 //out.println("Invalid Choice.. Go Back and choose again");
			request.setAttribute("invalidChoice", "Invalid Choice.. Go Back and choose again.");
			RequestDispatcher rd = request.getRequestDispatcher("views/teacher/assignmentSettings.jsp");
			rd.forward(request, response);
		 }
		 
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// Create path components to save the file
		final String new_folder="C:\\uploadedfiles";
	    final String folder1_path = new_folder+"\\"+request.getParameter("class_id");
	    
	   
	    	final String folder1=request.getParameter("class_id");
	    	final String folder2 = new_folder+"\\"+folder1+"\\Assignment";
	    	final String folder3=folder2+"\\"+request.getParameter("subject_name");
	    
		    boolean success=(new File(new_folder)).mkdir();
	   	 	if(success)
	   		  System.out.print("Directory "+new_folder+" created successfully");
	
		    success=(new File(folder1_path)).mkdir();
	   	 	if(success)
	   		  System.out.print("Directory "+folder1_path+" created successfully");
	
	   	 	success=(new File(folder2)).mkdir();
		 	if(success)
			  System.out.print("Directory "+folder2+" created successfully");
		    
		 	success=(new File(folder3)).mkdir();
		 	if(success)
			  System.out.print("Directory "+folder3+" created successfully");
		 	   path=folder3;
	   
	    
	    
	    final Part filePart = request.getPart("fileName");
	    final String fileName = getFileName(filePart);

	    OutputStream out = null;
	    InputStream filecontent = null;
	    //final PrintWriter writer = response.getWriter();
	    

	    try {
	    	
	        out = new FileOutputStream(new File(path + File.separator
	                + fileName));
	        filecontent = filePart.getInputStream();

	        int read = 0;
	        final byte[] bytes = new byte[1024];

	        while ((read = filecontent.read(bytes)) != -1) {
	            out.write(bytes, 0, read);
	        }
	        System.out.println("New file " + fileName + " created at " + path);
	       /* LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", 
	                new Object[]{fileName, path}); */
	    } catch (FileNotFoundException fne) {
	        message="You either did not specify a file to upload or are "
	                + "trying to upload a file to a protected or nonexistent "
	                + "location.";
	     
	        error=true;
	       
	       /* LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", 
	                new Object[]{fne.getMessage()}); */
	    } finally {
	        if (out != null) {
	            out.close();
	        }
	        if (filecontent != null) {
	            filecontent.close();
	        }
	       /* if (writer != null) {
	            writer.close();
	        } */
	    }

	    	processRequest(request, response);			
	      
	}
	
	private String getFileName(final Part part) {
	    final String partHeader = part.getHeader("content-disposition");
	   // LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
	    for (String content : part.getHeader("content-disposition").split(";")) {
	        if (content.trim().startsWith("filename")) {
	            return content.substring(
	                    content.indexOf('=') + 1).trim().replace("\"", "");
	        }
	    }
	    return null;
  }

}
